---
import type { GetStaticPaths } from 'astro';
import { getCollection } from 'astro:content';
import HomePage from '@anglefeint/astro-theme/layouts/HomePage.astro';
import HomeRedirectHead from '../../components/HomeRedirectHead.astro';
import { THEME } from '@anglefeint/site-config/theme';
import {
  DEFAULT_LOCALE,
  ENABLED_LOCALES,
  type Locale,
  getDefaultLocaleHomePath,
  isLocale,
  shouldRedirectLocalizedDefaultLocaleHome,
} from '@anglefeint/site-i18n/config';
import { postsForLocale } from '@anglefeint/site-i18n/posts';

export const getStaticPaths = (async () =>
  ENABLED_LOCALES.map((lang) => ({
    params: { lang },
  }))) satisfies GetStaticPaths;

const langParam = Astro.params.lang ?? DEFAULT_LOCALE;
const locale: Locale = isLocale(langParam) ? langParam : DEFAULT_LOCALE;
const shouldRedirect = shouldRedirectLocalizedDefaultLocaleHome(locale);
const localizedPosts = shouldRedirect ? [] : postsForLocale(await getCollection('blog'), locale);
const latestPosts = shouldRedirect ? [] : localizedPosts.slice(0, THEME.HOME_LATEST_COUNT);
const redirectHref = getDefaultLocaleHomePath();
---

{
  shouldRedirect ? (
    <html lang={DEFAULT_LOCALE}>
      <head>
        <HomeRedirectHead locale={locale} destination={redirectHref} />
      </head>
      <body>
        <p>
          Redirecting to <a href={redirectHref}>home</a>…
        </p>
      </body>
    </html>
  ) : (
    <HomePage locale={locale} latestPosts={latestPosts} totalPosts={localizedPosts.length} />
  )
}
